package main1;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhx
 * @since 2020-08-06
 */
public class MultiThread {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger count = new AtomicInteger();
        Lock lock = new ReentrantLock();
        Condition odd = lock.newCondition(); // ji shu
        Condition even = lock.newCondition(); // ou shu
        Thread t1 = new Thread(() -> {
            lock.lock();
            try {
                while (count.get() < 100) {
                    System.out.println(Thread.currentThread().getName() + " : " + count.getAndIncrement());
                    even.signal();
                }
                if (count.get() < 100) {
                    odd.await();
                }
            } catch (Exception e) {
                lock.unlock();
            }
        });
        Thread t2 = new Thread(() -> {
            lock.lock();
            try {
                while (count.get() < 100) {
                    System.out.println(Thread.currentThread().getName() + " : " + count.getAndIncrement());
                    odd.signal();
                }
                if (count.get() < 100) {
                    even.await();
                }
            } catch (Exception e) {
                lock.unlock();
            }

        });
        t1.start();
        Thread.sleep(1);
        t2.start();
    }


}

